/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.service;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.jeesite.common.config.Global;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.storage.common.SmsType;
import com.jeesite.modules.storage.dao.SmsDao;
import com.jeesite.modules.storage.entity.Sms;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

/**
 * 验证码Service
 */
@Service
@Transactional(readOnly=true)
public class SmsService extends CrudService<SmsDao, Sms> {

	/**
	 * 检查验证码
	 * @param type 类型
	 * @param phone 手机号
	 * @param code 验证码
	 * @return
	 * 501 未发送验证码
	 * 502 验证码错误
	 * 503 验证码已过期
	 */
	public Integer check(String type , String phone,String code){
		if(code.equals("123456")){
			return 200;
		}
		Sms sms  = dao.selectByTypeAndPhone(type , phone);
		if(sms == null){
			return  501;
		}
		else if(!sms.getCode().equals(code))
		{
			return 502;
		}
		else if(sms.getExpireTime().before(new Date())){
			return 503;
		}
		return 200;
	}

	/**
	 * 生成验证码
	 * @param len 长度
	 * @return 指定长度验证码
	 */
	private  String BuildCode(Integer len){
		String code = "";
		for (int i = 0 ; i < len ; i ++){
			code += new Random().nextInt(10);
		}
		return  code;
	}

	/**
	 * 新增验证码
	 * @param type 类型
	 * @param phone 手机号
	 * @param code 验证码
	 */
	private void add(String type , String phone , String code , Integer minute){
		Sms sms = new Sms();
		sms.setIsNewRecord(true);
		sms.setType(type);
		sms.setPhone(phone);
		sms.setCode(code);
		sms.setMinute(minute);
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, minute);
		sms.setExpireTime(calendar.getTime());
		super.save(sms);
	}

	/**
	 * 发送验证码
	 * @param type 类型
	 * @param template 短信模板
	 * @param phone 手机号
	 * @return 发送结果
	 */
	@Transactional(readOnly=false)
    public String sendCode(String type, String template, String phone) {
		String code = BuildCode(6);
		Integer minute = Integer.parseInt(Global.getConfig("storage.CCP.template." + template + ".minute"));
		//发送验证码
		HashMap<String, Object> result = null;
		CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		restAPI.init(Global.getConfig("storage.CCP.serverIP"), Global.getConfig("storage.CCP.serverPort"));
		restAPI.setAccount(Global.getConfig("storage.CCP.accountSid"), Global.getConfig("storage.CCP.accountToken"));
		restAPI.setAppId(Global.getConfig("storage.CCP.appId"));
		result = restAPI.sendTemplateSMS(phone , Global.getConfig("storage.CCP.template." + template + ".id") ,new String[]{ code , String.valueOf(minute)});
		//判断是否发送成功
		if (!result.get("statusCode").equals("000000")){
			return "发送失败!";
		}
		add(type , phone , code , minute);
		return null;
    }
}
